<?php

namespace App\Controller\Admin;

use App\Controller\Example\CartExample;
use App\Controller\Example\CartGoodsExample;
use App\Controller\Example\UserAddrExample;
use App\Models\AdminModel;
use App\Models\BarsGoodsModel;
use App\Models\CartGoodsModel;
use App\Models\CartModel;
use App\Models\Conn;
use App\Models\UsersAddrModel;
use Core\Common\Common;
use Core\Enums\ErrorEnum;
use Core\Result\Result;

class Order
{
    /**
     * 管理后台订单列表
     * entry token,uid,serial,username,truename,pay_type,status,startTime,endTime,page,limit
     * return json
     * */
    public function usersOrderList($data){
        $assemble = Common::assemble(new CartExample(), $data);
        $identical = Common::identical($data);
        $conn = new Conn();
        $joinSql = " WHERE c.`status` > 0 ";
        if($assemble->uid !=null){ $joinSql.=" and `uid` ='$assemble->uid' ";}
        if($assemble->serial !=null){ $joinSql.=" and `serial` ='$assemble->serial' ";}
        if($data["username"] !=null){ $joinSql.=" and u.`username` ='$data[username]' ";}
        if($data["truename"] !=null){ $joinSql.=" and u.`truename` ='$data[truename]' ";}
        if($assemble->pay_type !=null){ $joinSql.=" and `pay_type` ='$assemble->pay_type' ";}
        if($assemble->status !=null){ $joinSql.=" and c.`status` ='$assemble->status' ";}
        if($assemble->startTime !=null){ $assemble->startTime = strtotime($assemble->startTime);$joinSql.=" and UNIX_TIMESTAMP(`time`) >= '$assemble->startTime' ";}
        if($assemble->endTime !=null){ $assemble->endTime = strtotime($assemble->endTime);$joinSql.=" and UNIX_TIMESTAMP(`time`) <= '$assemble->endTime' ";}
        $sql = "SELECT c.`id`,`serial`,`uid`,`bid`,`price`,`pay_price`,`pay_amount`,c.`integral`,`pay_type`,c.`status`,`rtime`,`ptime`,`stime`,`time`,`addrid`,`remarks`,`courier_number`,`type`,u.`truename`,u.`username` FROM `cart` as c inner join `users` as u on c.uid = u.id $joinSql order by `time` desc limit $identical->pageStart,$identical->limit";
        $readConn = $conn->readConn($sql,true);
        $cartGoodsExample = new CartGoodsExample();
        foreach ($readConn as $item=>$value){
            switch ($value["status"]){
//                状态1，生成订单，2已结算/待支付 3已支付/待发货 4 已发货 5完成/已收货 6退货 -1删除/清空
                case 1:$readConn[$item]["status"]= "生成订单";break;
                case 2:$readConn[$item]["status"]= "已结算/待支付";break;
                case 3:$readConn[$item]["status"]= "已支付/待发货";break;
                case 4:$readConn[$item]["status"]= "已发货/待收货";break;
                case 5:$readConn[$item]["status"]= "完成";break;
                case 6:$readConn[$item]["status"]= "退款/售后";break;
            }
            switch ($value["pay_type"]){
                case "balance":$readConn[$item]["pay_type"]= "余额支付";break;
                case "alipay":$readConn[$item]["pay_type"]= "支付宝";break;
            }
            if($value["type"] == 1){
                $readConn[$item]["type"] = "正式单";
            }else{
                $readConn[$item]["type"] = "体验单";
            }
            $cartGoodsExample->uid = $value["uid"];
            $cartGoodsExample->cid = $value["id"];
            $userAddrExample = new UserAddrExample();
            $userAddrExample->uid = $value["uid"];
            $userAddrExample->id = $value["addrid"];
            $userAddr = UsersAddrModel::getUserAddr($conn, $userAddrExample);
            $readConn[$item]["userAddrName"] = $userAddr["name"];
            $readConn[$item]["userAddrMobile"] = $userAddr["mobile"];
            $readConn[$item]["userAddress"] = $userAddr["address"].$userAddr["detailed_address"];
            $cartGoodsInside = CartGoodsModel::getOrderCartGoodsInside($conn, $cartGoodsExample);
            foreach ($cartGoodsInside as $key=>$val){
                $cartGoodsInside[$key]["img"] = BarsGoodsModel::getGoodsSingle($conn,$val["gid"])["img"];
                $cartGoodsInside[$key]["sku"] = BarsGoodsModel::getGoodsSku($conn, $val["gid"], $val["sku_id"]);
            }
            $readConn[$item]["cartGoodsInfo"] = $cartGoodsInside;
        }
        $returnData["list"]=$readConn;
        $countSql="SELECT count(c.id) as count FROM `cart` as c inner join `users` as u on c.uid = u.id $joinSql";
        $totalSql="SELECT sum(price) as price,sum(pay_price) as pay_price,sum(pay_amount) as pay_amount,sum(c.integral) as integral FROM `cart` as c inner join `users` as u on c.uid = u.id $joinSql limit $identical->pageStart,$identical->limit";
        $returnData["count"] = $conn->readConn($countSql)["count"];
        $returnData["total"] = $conn->readConn($totalSql);
        Result::success($returnData);
    }
    /**
     * 订单发货
     * entry token,serial,courier_number
     * return json
     * */
    public function sendOutGoods($data){
        $assemble = Common::assemble(new CartExample(), $data);
        $conn = new Conn();
        $adminInToken = AdminModel::getAdminInToken($conn, $assemble->token);
        $cartInsideSerial = CartModel::getCartInsideSerial($conn, $assemble);
        if($cartInsideSerial["status"] != 3){
            Result::error(ErrorEnum::INVALIDORDER);
        }
        if(empty($assemble->courier_number)){
            Result::error(ErrorEnum::PLEASEFILLINTHEEXPRESSBILLNUMBER);
        }
        $assemble->status = 4;
        $assemble->id = $cartInsideSerial["id"];
        $assemble->uid = $cartInsideSerial["uid"];
        $conn->shiwuStart();
        if(CartModel::editCartInside($conn, $assemble) != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::SUBMITFAILED);
        }
        $conn->shiwuEnd();
        AdminLog::addAdminLog($adminInToken["username"],"订单管理","订单发货:[".$assemble->id."]");
        Result::success("ok");
    }
    /**
     * 确认退款
     * entry token,serial
     * return json
     * */
    public function confirmRefund($data){
        $assemble = Common::assemble(new CartExample(), $data);
        $conn = new Conn();
        $adminInToken = AdminModel::getAdminInToken($conn, $assemble->token);
        $cartInsideSerial = CartModel::getCartInsideSerial($conn, $assemble);
        if($cartInsideSerial["status"] != 6 && $cartInsideSerial["type"] != 2){
            Result::error(ErrorEnum::INVALIDORDER);
        }
        $assemble->status = 5;
        $assemble->id = $cartInsideSerial["id"];
        $assemble->uid = $cartInsideSerial["uid"];
        $conn->shiwuStart();
        if(CartModel::editCartInside($conn, $assemble) != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::SUBMITFAILED);
        }
        $conn->shiwuEnd();
        AdminLog::addAdminLog($adminInToken["username"],"订单管理","订单退款:[".$assemble->id."]");
        Result::success("ok");
    }
}